'use strict';
const qs = require('querystring');
const crypto = require('crypto');
const xml = require('node-xml');
const request = require('request');

const config = require('./config');

var wx_access_token = '';
var create_menu = false;

// 微信签名认证
exports.sign = function (req, res) {
    let signature = req.query.signature;
    let timestamp = req.query.timestamp;
    let nonce = req.query.nonce;
    let echostr = req.query.echostr;
    let token = config.token;

    let list = [token, timestamp, nonce];
    list.sort();
    let original = list.join('');
    let sha1 = crypto.createHash('sha1');
    sha1.update(original);
    let hashcode = sha1.digest('hex');
    console.log('sign compare:%s <==> %s', hashcode, signature);
    if (req.method == 'GET') {
        if (hashcode == signature) {
            res.send(echostr);
        } else {
            res.send('');
        }
    } else if (req.method == 'POST') {
        if (hashcode == signature) {
            return true;
        } else {
            return false;
        }
    }
    return true;
};

// 获取微信access_token
exports.getOAuthAccessToken = function (code, callback) {
    let queryParams = { 
        appid: config.appId,
        secret: config.appSecret,
        code: code,
        grant_type: 'authorization_code'
    };
    let url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' +
        qs.stringify(queryParams);
    let options = {
        method: 'GET',
        url: url
    };
    request(options, function (err, res, body) {
        if (res) {
            callback(false, JSON.parse(body));
        } else {
            callback(true, res);
        }
    });
};

// access_token在2小时内有效
exports.init = function () {
    saveToken();
    setInterval(function () {
        saveToken();
    }, 7000*1000);
};

// 获取access_token
function getAccessToken() {
    let queryParams = {
        grant_type: 'client_credential',
        appid: config.appId,
        secret: config.appSecret
    };

    let getTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token?' +
        qs.stringify(queryParams);
    let options = {
        method: 'GET',
        url: getTokenUrl
    };
    return new Promise((resolve, reject) => {
        request(options, function(err, res, body) {
            if (res) {
                resolve(JSON.parse(body));
            } else {
                reject(err);
            }
        });
    });
}

function saveToken() {
    getAccessToken().then(res => {
        if (typeof res.access_token === 'undefined') {
            console.error('get wechat token:' + res.errmsg);
        }
        wx_access_token = res.access_token;
        if (config.customerMenu && !create_menu) {
            create_menu = true;
            createMenu();
        }
    });
}

function createMenu() {
    let menus = {
        "button": [
            {
                "name": "游戏下载",
                "sub_button": [
                    {
                        "type": "view",
                        "name": "盟友杭州麻将",
                        "url": "http://fir.im/yakf"
                    },
                    {
                        "type": "view",
                        "name": "盟友缙云麻将",
                        "url": "http://fir.im/mjjy"
                    }
                ]
            },
            {
                "type": "view",
                "name": "代理登录",
                "url": "http://www.silinan.com/dealer-mobile/"
            }
        ]
    };
    let options = {
        method: 'POST',
        url: 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token=' + wx_access_token,
        form: JSON.stringify(menus),
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    };
    request.post(options, function(err, res, body) {
        if (err) {
            console.log(err);
        } else {
            console.log(body);
        }
    });
}



